package org.penguin.study.bk.remote;

import org.penguin.study.bk.base.vo.Result;
import org.penguin.study.bk.organization.entity.Organization;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;

@RestController
@RequestMapping("/remote/rest")
public class RemoteController {

    @Value("${server.port}")
    private int serverPort;
    @Autowired
    private RestTemplate restTemplate;

    // http://localhost:8090/remote/rest/organization/list?name=盛安德*
    @GetMapping("/organization/list")
    public Result<?> listOrganization(Organization organization) {
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        HttpEntity<Organization> entity = new HttpEntity<>(organization, headers);
        String url = "http://localhost:" + serverPort + "/organization/list?name="+ organization.getName();
        Result body = restTemplate.exchange(url,
                HttpMethod.GET, entity, Result.class).getBody();
        return body;
    }

    @PostMapping("/organization/create")
    public Result<?> createOrganization(@RequestBody Organization organization) {
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        HttpEntity<Organization> entity = new HttpEntity<>(organization, headers);
        String url = "http://localhost:" + serverPort + "/organization/add";
        Result body = restTemplate.exchange(url,
                HttpMethod.POST, entity, Result.class).getBody();
        return body;
    }
}
